package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsAssistDeliveryMapper;
import com.jy.wms.dao.WmsPdaAssistDeliveryMapper;
import com.jy.wms.dao.WmsPdaMsgMapper;
import com.jy.wms.pojo.SysHz;
import com.jy.wms.pojo.WmsAssistDelivery;
import com.jy.wms.pojo.WmsPdaAssistDelivery;
import com.jy.wms.pojo.WmsPdaMsg;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
    * @ClassName: WmsAssistDeliveryService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Liyi
    * @Date Thu Mar 15 11:02:40 CST 2018
    */

    @Service
    public class WmsAssistDeliveryService extends BaseService<WmsAssistDeliveryMapper,WmsAssistDelivery> {

        @Autowired
        private WmsPdaMsgMapper wmsPdaMsgMapper;
        @Autowired
        private WmsPdaAssistDeliveryMapper wmsPdaAssistDeliveryMapper;

    /**
     * 上传文件导入EXCEL
     * @param filepath
     * @return
     */
    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "上传EXCEL文件导入")
    public void upload(String  filepath,String ckid)throws SucessException,Exception{

        JSONObject jb = JSONObject.fromObject(filepath);
        String fileName = (String) jb.get("filepath");
        URL url = new URL(fileName);
        URLConnection conn = url.openConnection();
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setDataHanlder(new AssistDeliveryMapImportHanlder());
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                conn.getInputStream(),
                Map.class, params);
        WmsAssistDelivery wmsAssistDelivery = null;
        Integer count = 0;
        Integer sum = 0;
        StringBuffer message = new StringBuffer();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < result.size(); i++) {
            try {
                sum ++;
                wmsAssistDelivery = new WmsAssistDelivery();
                for(int j=0;j<result.get(i).size();j++){
                    wmsAssistDelivery.setId(UUIDUtils.uuid());
                    wmsAssistDelivery.setCkid(ckid);
                    wmsAssistDelivery.setFqbm(result.get(i).get("fqbm") == null ? "" : result.get(i).get("fqbm").toString());
                    wmsAssistDelivery.setFqr(result.get(i).get("fqr") == null ? "" : result.get(i).get("fqr").toString());
                    wmsAssistDelivery.setYt(result.get(i).get("yt") == null ? "" : result.get(i).get("yt").toString());
//                    wmsAssistDelivery.setLsh(result.get(i).get("lsh").toString());
                    wmsAssistDelivery.setDdh(result.get(i).get("ddh") == null ? "" : result.get(i).get("ddh").toString());
                    wmsAssistDelivery.setDdhbfydh(result.get(i).get("ddhbfydh") == null ? "" : result.get(i).get("ddhbfydh").toString());
                    wmsAssistDelivery.setFhfs(result.get(i).get("fhfs") == null ? "" : result.get(i).get("fhfs").toString());
                    wmsAssistDelivery.setYfcdf(result.get(i).get("yfcdf") == null ? "" : result.get(i).get("yfcdf").toString());
                    wmsAssistDelivery.setShrxm(result.get(i).get("shrxm") == null ? "" : result.get(i).get("shrxm").toString());
                    wmsAssistDelivery.setShrgj(result.get(i).get("shrgj") == null ? "" : result.get(i).get("shrgj").toString());
                    wmsAssistDelivery.setSf(result.get(i).get("sf") == null ? "" : result.get(i).get("sf").toString());
                    wmsAssistDelivery.setCs(result.get(i).get("cs") == null ? "" : result.get(i).get("cs").toString());
                    wmsAssistDelivery.setXq(result.get(i).get("xq") == null ? "" : result.get(i).get("xq").toString());
                    wmsAssistDelivery.setShdz(result.get(i).get("shdz") == null ? "" : result.get(i).get("shdz").toString());
                    wmsAssistDelivery.setLxdh(result.get(i).get("lxdh") == null ? "" : result.get(i).get("lxdh").toString());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                    if(!(result.get(i).get("fqrq").equals(""))){
//                        wmsAssistDelivery.setFqrq(sdf.format(HSSFDateUtil.getJavaDate(Integer.valueOf(result.get(i).get("fqrq").toString()))));
//                    }
                    if(result.get(i).get("zfrq") != null && !(result.get(i).get("zfrq").equals(""))){
                        wmsAssistDelivery.setZfrq(sdf.format(HSSFDateUtil.getJavaDate(Integer.valueOf(result.get(i).get("zfrq").toString()))));
                    }
//                    wmsAssistDelivery.setFwbh(result.get(i).get("fwbh").toString());
                    wmsAssistDelivery.setCpmc(result.get(i).get("cpmc") == null ? "" : result.get(i).get("cpmc").toString());
                    wmsAssistDelivery.setSl(result.get(i).get("sl") == null ? "" : result.get(i).get("sl").toString());
                    wmsAssistDelivery.setGg(result.get(i).get("gg") == null ? "" : result.get(i).get("gg").toString());
                    wmsAssistDelivery.setDw(result.get(i).get("dw") == null ? "" : result.get(i).get("dw").toString());
                    wmsAssistDelivery.setCplb(result.get(i).get("cplb") == null ? "" : result.get(i).get("cplb").toString());
                    wmsAssistDelivery.setDj(result.get(i).get("dj") == null ? "" : result.get(i).get("dj").toString());
                    wmsAssistDelivery.setTdwldh(result.get(i).get("tdwldh") == null ? "" : result.get(i).get("tdwldh").toString());
                    wmsAssistDelivery.setHh(result.get(i).get("hh") == null ? "" : result.get(i).get("hh").toString());
//                    wmsAssistDelivery.setFhzy(result.get(i).get("fhzy").toString());
                    wmsAssistDelivery.setBz(result.get(i).get("bz") == null ? "" : result.get(i).get("bz").toString());
                    wmsAssistDelivery.setXgsj(simpleDateFormat.format(System.currentTimeMillis()));
                }
                //如果 订单号、省份、城市、县区、收货地址、联系电话、收货人姓名 存在空值则不允许导入
                if("".equals(wmsAssistDelivery.getDdh()) || "".equals(wmsAssistDelivery.getSf()) || "".equals(wmsAssistDelivery.getCs()) || "".equals(wmsAssistDelivery.getXq()) ||
                    "".equals(wmsAssistDelivery.getShdz()) || "".equals(wmsAssistDelivery.getLxdh()) || "".equals(wmsAssistDelivery.getShrxm())){
                    if(message.length() > 0) {
                        message.append("," + (wmsAssistDelivery.getDdh() == null ? " ": wmsAssistDelivery.getDdh()));
                    }else {
                        message.append("订单号：" + (wmsAssistDelivery.getDdh() == null ? " ": wmsAssistDelivery.getDdh()));
                    }
                    continue;
                }
                dao.baseInsertSelective(wmsAssistDelivery);
                count ++ ;
            }catch (Exception e) {
                if(message.length() > 0) {
                    message.append("," + (wmsAssistDelivery.getDdh() == null ? " ": wmsAssistDelivery.getDdh()));
                }else {
                    message.append("订单号：" + (wmsAssistDelivery.getDdh() == null ? " ": wmsAssistDelivery.getDdh()));
                }
                e.printStackTrace();
            }
        }
        throw new SucessException("导入EXCEL成功，总共" + sum + "条，成功" + count + "条" + (message.length()>0 ? "," + message.toString() + "订单号重复或信息不完整。" : "。"));
    }

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsAssistDelivery entity){
         return dao.baseInsert( entity );
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective( WmsAssistDelivery entity){
         return dao.baseInsertSelective( entity);
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
   @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "删除")
    public void baseDeleteBathPrimaryKeys( List<String> idList)throws SucessException,Exception{
         dao.baseDeleteBathPrimaryKeys( idList );
       throw new SucessException();
    }

    /**
     * 下发PDA
     * @param setAndModifyModel 主键ID列表
     * @return int
     */
    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "下发PDA")
    @Transactional
    public void xfpda( SetAndModifyModel setAndModifyModel, HttpSession session)throws SucessException,ServiceException,Exception{
        //获取PC端不可发运数量
        List<String> list =  dao.getBkfysl(setAndModifyModel.getIds());
        if(list.size() > 0){
            StringBuffer message = new StringBuffer();
            message.append("下发PDA失败，订单号：");
            for (String s : list) {
                message.append(s + ",");
            }
            message.append("已下发");
            throw new ServiceException(message.toString());
        }
        //修改fyzt = 1
        dao.updatePdaxf(setAndModifyModel.getIds());

        //向PDA装车任务表写信息
        List<WmsAssistDelivery> contentList =  dao.baseSelectBathPrimaryKeys(setAndModifyModel.getIds());
        WmsPdaAssistDelivery wmsPdaAssistDelivery = new WmsPdaAssistDelivery();
        for (WmsAssistDelivery wmsAssistDelivery : contentList) {
            wmsPdaAssistDelivery.setId(UUIDUtils.uuid());
            wmsPdaAssistDelivery.setXzfhid(wmsAssistDelivery.getId());
            wmsPdaAssistDelivery.setRyid(setAndModifyModel.getId());
            wmsPdaAssistDelivery.setShrxm(wmsAssistDelivery.getShrxm());
            wmsPdaAssistDelivery.setDdh(wmsAssistDelivery.getDdh());
            wmsPdaAssistDelivery.setKdgs(wmsAssistDelivery.getFhfs());
            wmsPdaAssistDelivery.setKddh(wmsAssistDelivery.getKddh());
            wmsPdaAssistDelivery.setKhdh(wmsAssistDelivery.getLxdh());
            wmsPdaAssistDelivery.setZcdh(wmsAssistDelivery.getZcdbh());
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            wmsPdaAssistDelivery.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
            if(hz.size() > 0){
                wmsPdaAssistDelivery.setHzid(hz.get(0).getHzid());
            }
            wmsPdaAssistDeliveryMapper.baseInsertSelective(wmsPdaAssistDelivery);
        }
        //生成PDA消息推送
        WmsPdaMsg wmsPdaMsg = new WmsPdaMsg();
        wmsPdaMsg.setRyid(setAndModifyModel.getId());
        wmsPdaMsg.setBt("协助发运");
        wmsPdaMsg.setXx(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()) + " 下发协助发运任务");
        Integer msgCount = wmsPdaMsgMapper.baseInsertSelective(wmsPdaMsg);
        if(msgCount == 0){
            throw new RuntimeException("下发协助发运任务失败，数据未插入数据库");
        }
        throw new SucessException();
    }

    /**
     * PC端发运
     * @param idList 主键ID列表
     * @return int
     */
    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "PC端发运")
    public void pcfy( List<String> idList)throws SucessException,ServiceException,Exception{
        //获取PC端不可发运数量
       List<WmsAssistDelivery> list =  dao.baseSelectBathPrimaryKeys(idList);
        List<String> ddhs =  dao.getBkfysl(idList);
       if(ddhs.size() > 0){
           StringBuffer message = new StringBuffer();
           message.append("发运失败，订单号：");
           for (String s : ddhs) {
               message.append(s + ",");
           }
           message.append("已下发");
           throw new ServiceException(message.toString());
       }
        for (WmsAssistDelivery wmsAssistDelivery : list) {
            Map<String, Object> message = HttpUtil.message(wmsAssistDelivery.getShrxm(), wmsAssistDelivery.getLxdh(), wmsAssistDelivery.getDdh(),wmsAssistDelivery.getKddh());
            boolean flag = (boolean) message.get("type");
            if (!flag) {
                if (!"".equals(message.get("msg")) && message.get("msg") != null) {
                    throw new ServiceException("短信发送失败:" + message.get("msg").toString());
                } else {
                    throw new ServiceException("短信发送失败");
                }
            }
        }
       //修改fyzt = 3
        dao.updatePcfy(idList);
        throw new SucessException();
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsAssistDelivery>
    */
    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "分页查询")
    public Page<WmsAssistDelivery> baseSelectPage(WmsAssistDelivery entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<WmsAssistDelivery>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsAssistDelivery
    */
    public WmsAssistDelivery baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }


    /**
     * 根据订单号查询
     * @param ddh 订单号
     * @return WmsAssistDelivery
     */
    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "根据订单号查询")
    public WmsAssistDelivery findByDdh( String ddh ){
        return dao.findByDdh( ddh );
    }

    @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "打印快递面单")
    @Transactional
    public String print(String id,String sjzl)throws ServiceException,Exception{
        String message = "";
        JSONObject json = new JSONObject();
        WmsAssistDelivery wmsAssistDelivery = dao.baseSelectByPrimaryKey( id );
        wmsAssistDelivery.setSjzl(sjzl);
        //计算快递价格
        wmsAssistDelivery.setYf(new HttpUtil().computationalCosts(wmsAssistDelivery,Double.valueOf(sjzl)).toString());
        wmsAssistDelivery.setFhfs(ckfhInfo.fydd_dx_kdgs.getType());
        dao.baseUpdateByPrimaryKeySelective(wmsAssistDelivery);
        //打印快递面单
        json.put("partnerId",ckfhInfo.ckfh_partnerId.getType());
        json.put("net", ckfhInfo.ckfh_net.getType());
        json.put("partnerKey", ckfhInfo.ckfh_partnerKey.getType());
        json.put("kuaidicom", ckfhInfo.ckfh_kuaidicom.getType());
        json.put("kuaidinum", "");
        json.put("orderId", "");
        JSONObject sendMan = new JSONObject();
        sendMan.put("name", ckfhInfo.ckfh_sendMan_name.getType());
        sendMan.put("mobile", ckfhInfo.ckfh_sendMan_mobile.getType());
        sendMan.put("tel", ckfhInfo.ckfh_sendMan_tel.getType());
        sendMan.put("province", ckfhInfo.ckfh_sendMan_province.getType());
        sendMan.put("city", ckfhInfo.ckfh_sendMan_city.getType());
        sendMan.put("district", ckfhInfo.ckfh_sendMan_district.getType());
        sendMan.put("addr", ckfhInfo.ckfh_sendMan_addr.getType());
        sendMan.put("printAddr", ckfhInfo.ckfh_sendMan_printAddr.getType());
        sendMan.put("company", ckfhInfo.ckfh_sendMan_company.getType());
        json.put("sendMan", sendMan);
        JSONObject recMan = new JSONObject();
        recMan.put("name", wmsAssistDelivery.getShrxm());
        recMan.put("mobile", wmsAssistDelivery.getLxdh());
        recMan.put("province", wmsAssistDelivery.getSf());
        recMan.put("city", wmsAssistDelivery.getCs());
        recMan.put("district", wmsAssistDelivery.getXq());
        recMan.put("addr", wmsAssistDelivery.getShdz());
        recMan.put("printAddr", "");
        recMan.put("company", "");
        json.put("recMan", recMan);
        json.put("cargo", wmsAssistDelivery.getCplb());
        json.put("count", wmsAssistDelivery.getSl());
        json.put("weight", wmsAssistDelivery.getSjzl());
        json.put("volumn", "");
        json.put("payType", "");
        json.put("expType", ckfhInfo.ckfh_expType.getType());
        json.put("remark", "");
        json.put("valinsPay", new Double(0));
        json.put("collection", new Double(0));
        json.put("needChild",ckfhInfo.ckfh_needChild.getType());
        json.put("needBack", ckfhInfo.ckfh_needBack.getType());
        json.put("needTemplate", ckfhInfo.ckfh_needTemplate.getType());

        Long t = System.currentTimeMillis();
        String key = ckfhInfo.ckfh_key.getType();
        String secret = ckfhInfo.ckfh_secret.getType();

        Map<String, Object> params = new HashMap<String, Object>();
        System.out.println("原文：" + json.toString() + t + key + secret);
        logger.info("原文：" + json.toString() + t + key + secret);
        String sign = MD5.encode(json.toString() + t + key + secret);
        System.out.println("sign:" + sign);
        params.put("method", "getElecOrder");
        params.put("param", json.toString());
        params.put("sign", sign);
        params.put("t", t.toString());
        params.put("key", key);
        System.out.println(params.toString());
        json = JSONObject.fromObject(HttpUtil.doPost("http://api.kuaidi100.com/eorderapi.do", params).toString());
        json.toString();
        if(!(json.get("status").toString().equals("200"))){
            throw new ServiceException(json.get("message").toString());
        }else{
            json = JSONObject.fromObject(JSONArray.fromObject(json.get("data").toString()).get(0));
            message = json.get("templateurl").toString();
            //更新快递单号
            wmsAssistDelivery.setKddh(json.get("kuaidinum").toString());
            dao.updateHddh(wmsAssistDelivery);
        }
        return message;
    }



    /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public List<WmsAssistDelivery> baseSelectBathPrimaryKeys( List<String> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
   @BaseServiceDescribe(moduleName = "协助发货相关操作",btnName = "修改 （匹配有值的字段）")
    public void baseUpdateByPrimaryKeySelective( WmsAssistDelivery entity) throws SucessException,ServiceException{
       WmsAssistDelivery wmsAssistDelivery = dao.baseSelectByPrimaryKey(entity.getId());
       if(wmsAssistDelivery.getXfzt().equals("0") && wmsAssistDelivery.getZcdbh().equals("0")){
           Integer count = dao.baseUpdateByPrimaryKeySelective( entity);
           if(count > 0){
               throw new SucessException("编辑信息成功");
           }else{
               throw new ServiceException("编辑信息失败，未加入数据库");
           }
       }
       throw new ServiceException("改订单已加入装车或已下发任务无法编辑信息");
   }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsAssistDelivery entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }

    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }

}
